package beer.coder.walawala.gui.component;

import beer.coder.walawala.common.config.ApplicationConfigure;
import beer.coder.walawala.common.constant.Constant;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import javafx.application.Platform;
import javax.swing.JDialog;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

/**
 * 系统图标.
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-26 20:59
 */
public class WaTrayIcon extends TrayIcon {

  static final int MARGIN = 3;
  JDialog dialog;
  JPopupMenu menu;

  public WaTrayIcon(Image image, String tooltip, JPopupMenu menu) {
    super(image, tooltip);
    this.menu = menu;

    setImageAutoSize(true);
    initDialog();
    setupListeners();
  }


  void initDialog() {
    dialog = new JDialog();
    dialog.setUndecorated(true);
    dialog.setAlwaysOnTop(true);
  }

  void setupListeners() {
    this.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseReleased(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && menu != null) {
              Dimension size = menu.getPreferredSize();
              dialog.setLocation(e.getX() - size.width - MARGIN, e.getY() - size.height - MARGIN);
              dialog.setVisible(true);

              menu.show(dialog.getContentPane(), 0, 0);
            }
          }
        });

    menu.addPopupMenuListener(
        new PopupMenuListener() {
          @Override
          public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
          }

          @Override
          public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            dialog.setVisible(false);
          }

          @Override
          public void popupMenuCanceled(PopupMenuEvent e) {
            dialog.setVisible(false);
          }
        });
  }
}
